package com.xunlai.infra.permission.manager.authority.sercurity.passowrd;

import com.xunlai.infra.permission.common.util.SM2Utils;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author liang
 * @date 12/7/22 5:39 PM
 */
public class SM2PasswordEncoder implements PasswordEncoder {
    private final PrivateKey privateKey;

    private final PublicKey publicKey;

    public SM2PasswordEncoder(PrivateKey privateKey, PublicKey publicKey) {
        this.privateKey = privateKey;
        this.publicKey = publicKey;
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return SM2Utils.encrypt(privateKey,rawPassword.toString());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return SM2Utils.verify(publicKey,encodedPassword,rawPassword.toString());
    }

    public static void main(String[] args) {
        SM2PasswordEncoder passwordEncoder = new SM2PasswordEncoder(SM2Utils.loadPrivateKey("308193020100301306072a8648ce3d020106082a811ccf5501822d0479307702010104206d4cbfeee79eae5f20026cfbf3fcd9bdabce059a546bfc73eee868fb2ff0225aa00a06082a811ccf5501822da1440342000438cbe3333b5c9b470cd7c8c4ce4d5e0da39902348e7cf9700ec30d43ba3db4d4b5e7d295719bf09862fdc4d9caf29f69f4c9c69ff260979c0e7ac90d775959af"),SM2Utils.loadPublicKey("3059301306072a8648ce3d020106082a811ccf5501822d0342000438cbe3333b5c9b470cd7c8c4ce4d5e0da39902348e7cf9700ec30d43ba3db4d4b5e7d295719bf09862fdc4d9caf29f69f4c9c69ff260979c0e7ac90d775959af"));
        String encode = passwordEncoder.encode("629516");
        System.out.println(encode);
    }
}
